/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import Entity.Owner;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entity.Pet;
import Services.exceptions.NonexistentEntityException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Grace
 */
public class OwnerService implements Serializable {

    public OwnerService(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Owner owner) {
        if (owner.getPets() == null) {
            owner.setPets(new ArrayList<Pet>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Pet> attachedPets = new ArrayList<Pet>();
            for (Pet petsPetToAttach : owner.getPets()) {
                petsPetToAttach = em.getReference(petsPetToAttach.getClass(), petsPetToAttach.getId());
                attachedPets.add(petsPetToAttach);
            }
            owner.setPets(attachedPets);
            em.persist(owner);
            for (Pet petsPet : owner.getPets()) {
                Owner oldOwnerOfPetsPet = petsPet.getOwner();
                petsPet.setOwner(owner);
                petsPet = em.merge(petsPet);
                if (oldOwnerOfPetsPet != null) {
                    oldOwnerOfPetsPet.getPets().remove(petsPet);
                    oldOwnerOfPetsPet = em.merge(oldOwnerOfPetsPet);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Owner owner) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Owner persistentOwner = em.find(Owner.class, owner.getId());
            List<Pet> petsOld = persistentOwner.getPets();
            List<Pet> petsNew = owner.getPets();
            List<Pet> attachedPetsNew = new ArrayList<Pet>();
            for (Pet petsNewPetToAttach : petsNew) {
                petsNewPetToAttach = em.getReference(petsNewPetToAttach.getClass(), petsNewPetToAttach.getId());
                attachedPetsNew.add(petsNewPetToAttach);
            }
            petsNew = attachedPetsNew;
            owner.setPets(petsNew);
            owner = em.merge(owner);
            for (Pet petsOldPet : petsOld) {
                if (!petsNew.contains(petsOldPet)) {
                    petsOldPet.setOwner(null);
                    petsOldPet = em.merge(petsOldPet);
                }
            }
            for (Pet petsNewPet : petsNew) {
                if (!petsOld.contains(petsNewPet)) {
                    Owner oldOwnerOfPetsNewPet = petsNewPet.getOwner();
                    petsNewPet.setOwner(owner);
                    petsNewPet = em.merge(petsNewPet);
                    if (oldOwnerOfPetsNewPet != null && !oldOwnerOfPetsNewPet.equals(owner)) {
                        oldOwnerOfPetsNewPet.getPets().remove(petsNewPet);
                        oldOwnerOfPetsNewPet = em.merge(oldOwnerOfPetsNewPet);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = owner.getId();
                if (findOwner(id) == null) {
                    throw new NonexistentEntityException("The owner with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Owner owner;
            try {
                owner = em.getReference(Owner.class, id);
                owner.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The owner with id " + id + " no longer exists.", enfe);
            }
            List<Pet> pets = owner.getPets();
            for (Pet petsPet : pets) {
                petsPet.setOwner(null);
                petsPet = em.merge(petsPet);
            }
            em.remove(owner);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Owner> findOwnerEntities() {
        return findOwnerEntities(true, -1, -1);
    }

    public List<Owner> findOwnerEntities(int maxResults, int firstResult) {
        return findOwnerEntities(false, maxResults, firstResult);
    }

    private List<Owner> findOwnerEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Owner.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
    
    public Owner findOwnerEntitiesByNameOrSsn(String name){
        EntityManager em = getEntityManager();
        Query query = em.createQuery("select o from Person o where o.idPerson.name=:name or o.idPerson.ssn=:ssn").setParameter("name", name).setParameter("ssn", name);
        if(!query.getResultList().isEmpty()) {
            return (Owner) query.getSingleResult();
        }
        else{
            return null;
        }
    }

    public Owner findOwner(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Owner.class, id);
        } finally {
            em.close();
        }
    }

    public int getOwnerCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Owner> rt = cq.from(Owner.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
